package com.zj.web.controller;

import com.zj.service.GrabResult;
import com.zj.service.RedPacketService;
import com.zj.service.UserRedPacketService;
import com.zj.web.bean.RedPacketActivityDTO;
import com.zj.web.bean.ResponseResult;
import com.zj.web.bean.UserRedPacketDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/redpackets")
@RefreshScope //开启动态刷新
public class RedPacketController {
    @Autowired
    private RedPacketService redPacketService;
    @Autowired
    private UserRedPacketService userRedPacketService;
    //发红包，添加红包活动到数据库
    @PostMapping("/publish")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<ResponseResult> publishRedPacket(RedPacketActivityDTO redPacketActivityDTO){
        RedPacketActivityDTO redPacketActivityDTO1 = redPacketService.publishRedPacket(redPacketActivityDTO);
        return ResponseEntity.ok(ResponseResult.ok().setdata(redPacketActivityDTO1));
    }
    //抢红包
    @GetMapping("/grab/{redPacketId}/{userId}")
    public ResponseEntity<ResponseResult> grabRedPacket(@PathVariable("redPacketId") Long redPacketId,
                                                        @PathVariable("userId") Long userId) {
        //获取当前认证用户的id(从Gateway 传递的 X-User-Id)
        String currentUserId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断当前用户是否是要查询的用户
        //如果请求的ID不是当前用户的id，则拒绝访问
        if(!currentUserId.equals(userId.toString())){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error("没有权限抢当前id的红包"));
        }
        GrabResult result = redPacketService.grabRedPacket(redPacketId, userId);
        return ResponseEntity.ok(ResponseResult.builder().code(1).msg("查询成功").data(result).build());
    }
    //根据用户id查询领取过的红包活动信息
    @GetMapping("/user/{userId}")
    public ResponseEntity<ResponseResult> findByUserId(@PathVariable("userId") Long userId) {
        //获取当前认证用户的id(从Gateway 传递的 X-User-Id)
        String currentUserId = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //判断当前用户是否是要查询的用户
        //如果请求的ID不是当前用户的id，则拒绝访问
        if(!currentUserId.equals(userId.toString())){
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body(ResponseResult.error("没有权限查询当前id的红包"));
        }
        List<UserRedPacketDTO> userRedPackets = userRedPacketService.findByUserId(userId);
        return ResponseEntity.ok(ResponseResult.builder().code(1).msg("查询成功").data(userRedPackets).build());
    }
}
